package cc.orange.mainView;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;

import com.donkingliang.imageselector.utils.ImageSelector;
//import com.tendcloud.tenddata.TalkingDataSDK;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import cc.orange.BuildConfig;
import cc.orange.R;
import cc.orange.adapter.MsgConAdapter;
import cc.orange.base.BaseActivity;
import cc.orange.databinding.ActivityConversationListBinding;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.BaseStrEntity;
import cc.orange.entity.ConveListEntity;
import cc.orange.entity.IsLoginsEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.PopupSoftinputUtils;
import cc.orange.utils.RequestPermissions;
import cc.orange.utils.ScreenUtils;
import cc.orange.utils.SoftKeyBoardListener;
import cc.orange.utils.ZXToastUtil;
import cc.orange.utils.emojis.EmoticonBoard;
import cc.orange.utils.emojis.RongUtils;
import cc.orange.utils.popup.PopupUtils;
import demo.smart.access.xutlis.util.ZXAppUtil;
import demo.smart.access.xutlis.util.ZXSystemUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.http.Query;

import static demo.smart.access.xutlis.views.PhotoPicker.PhotoPicker.REQUEST_CODE;

public class ConversationListActivity extends BaseActivity implements View.OnClickListener{

    private ActivityConversationListBinding binding;
    private String uid;
    private  String u_spare;
    private MsgConAdapter adapter;
    private String type_t;
    private List<ConveListEntity.Data.Lists> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_conversation_list);
        uid = getIntent().getStringExtra("uid");
        String u_name = getIntent().getStringExtra("u_name");
        u_spare = getIntent().getStringExtra("u_spare");
        type_t = getIntent().getStringExtra("type_t");
        binding.converListTitle1.setText(u_name);
        binding.inputPanelEmojiBtn.setOnClickListener(this);
        getKeyBoard();
        initViews();
        findChat();
        EventBus.getDefault().register(this);
    }



    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
//            chatAnswer(uid);
            list.clear();
            findChat();
        }
    };

    private void initViews() {
        RelativeLayout.LayoutParams pp = new RelativeLayout.
                LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ScreenUtils.getStatusBarHeight(ConversationListActivity.this));
        binding.talktabTop.setLayoutParams(pp);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        linearLayoutManager.setStackFromEnd(true);
        binding.talkMsgList.setLayoutManager(linearLayoutManager);
        adapter = new MsgConAdapter(list);
        binding.talkMsgList.setAdapter(adapter);

        TextWatcher mTextWatcher = new TextWatcher() {
            private int start;
            private int count;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (AndroidEmoji.isEmoji(s.subSequence(start, start + count).toString())) {
//                    binding.editBtn.removeTextChangedListener(this);
//                    String resultStr = AndroidEmoji.replaceEmojiWithText(s.toString());
//                    binding.editBtn.setText(AndroidEmoji.ensure(resultStr), TextView.BufferType.SPANNABLE);
//                    binding.editBtn.setSelection(binding.editBtn.getText().length());
//                    binding.editBtn.addTextChangedListener(this);
//                }
//                String s1 = binding.editBtn.getText().toString();
//                if(TextUtils.isEmpty(s1)){
//                    binding.talkSend.setBackgroundResource(R.drawable.shape_8e_13);
//                }else{
//                    binding.talkSend.setBackgroundResource(R.drawable.shape_home_title);
//                }
            }
        };

        binding.talkSend.addTextChangedListener(mTextWatcher);


        binding.talkSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s1 = binding.editBtn.getText().toString();
                if(!TextUtils.isEmpty(s1)){
                    saveChat(uid,s1,0);
                    forceSetSoftInputKeyBoard(false);
                    binding.editBtn.setText("");
                }
            }
        });

        binding.msginfoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //个人消息
        binding.conveImg1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ConversationListActivity.this,InfoMsgActivity.class);
                intent.putExtra("typs_where", 1);
                intent.putExtra("uids",uid);
                intent.putExtra("spares",u_spare);
                startActivity(intent);
            }
        });

        //图片
        binding.convImg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopuSelect();
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
//        EventBus.getDefault().post(new IsLoginsEntity(true));
//        TalkingDataSDK.onPageEnd(this, getLocalClassName());
    }

    public void forceSetSoftInputKeyBoard(boolean isShow) {
        InputMethodManager imm = (InputMethodManager) getApplication().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            if (isShow) {
                binding.editBtn.requestFocus();
                imm.showSoftInput(binding.editBtn, 0);
            } else {
                imm.hideSoftInputFromWindow(binding.editBtn.getWindowToken(), 0);
                binding.editBtn.clearFocus();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.input_panel_emoji_btn:
                forceSetSoftInputKeyBoard(false);
                EmoticonBoard mEmoticonBoard = new EmoticonBoard(ConversationListActivity.this, binding.talkeRel1, "123",binding.editBtn);
                binding.converRel1.removeAllViews();
                binding.converRel1.addView(mEmoticonBoard.getView());

                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.converRel1.getLayoutParams();
                layoutParams.height = RongUtils.dip2px(230);
                binding.converRel1.setLayoutParams(layoutParams);
                break;
        }
    }


    public void getKeyBoard(){

        //监听软键盘弹出，并获取软键盘高度
        SoftKeyBoardListener.setListener(ConversationListActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //软键盘弹起事件  并给View设置高度
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.converRel1.getLayoutParams();
                layoutParams.height = RongUtils.dip2px(0);
                binding.converRel1.setLayoutParams(layoutParams);
            }

            @Override
            public void keyBoardHide(int height) {
                //软键盘隐藏事件  并给View设置高度为0
            }
        });
    }


    // 查找聊天记录
    private void findChat(){//消息列表类型(0首页消息,1悄悄话消息)
        String s = "{\"sendSpareStatus\":\""+u_spare+"\",\"womanId\":\""+uid+"\",\"type\":\""+type_t+"\"}";
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .findChat(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<ConveListEntity>() {
                    @Override
                    public void onStart(Call<ConveListEntity> call) {
                    }

                    @Override
                    public void onError(Call<ConveListEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<ConveListEntity> call, ConveListEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            list.addAll(baseEntity.getData().getList());
                            Collections.reverse(list);
                            ConveListEntity.Data.Lists lls = new ConveListEntity.Data.Lists();
                            lls.setId(-112);
                            list.add(0,lls);

                            adapter.setNamePhoto(baseEntity.getData().getName(),baseEntity.getData().getPhoto(),uid);
                            adapter.notifyDataSetChanged();
                            if(list.size() > 1) {
                                binding.talkMsgList.smoothScrollToPosition(adapter.getItemCount() - 1);
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                        if(list.size() > 0) {
                            handler.sendEmptyMessageDelayed(0, 10000);
                        }
                    }
                });
    }

    // 保存聊天信息
    private void saveChat(String uid,String content,int types){

        String s = "{\"womanId\":\""+uid+"\",\"chat\":\""+content+"\",\"sendSpareStatus\":\""+u_spare+"\"," +
                "\"packageName\":\""+ZXAppUtil.getPackageName()+"\",\"channel\":\""+BuildConfig.APP_CHANNEL+
                "\",\"version\":\""+ZXSystemUtil.getVersionCode()+"\",\"informationType\":\""+types+"\",\"type\":\""+type_t+"\"}";
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .saveChat(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){

                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }

                        handler.removeMessages(0);
                        handler.sendEmptyMessageDelayed(0, 100);
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
//        TalkingDataSDK.onPageBegin(this, getLocalClassName());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHight(String entity){
        if(entity.equals("conver_finish")){
            EventBus.getDefault().post(new String("home_refres"));
            finish();
        }

        if(entity.contains("remarke")){
            String[] s = entity.split("_");
            binding.converListTitle1.setText(s[1]);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(0);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                upImg(images.get(0));
            }
        }
    }

    public void upImg(String path) {
        IdentityHashMap<String, RequestBody> params = new IdentityHashMap<String, RequestBody>();
        try {
            File file = new File(path);
//                File file1 = new Compressor(this).compressToFile(file);
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
            params.put(new String("file" + "\"" + "; filename=\"adfas.png"), requestFile);
        } catch (Exception e) {
            demo.smart.access.xutlis.util.ZXToastUtil.showToast("图片格式出错，请重试或联系管理员");
            e.printStackTrace();
        }
        RetrofitFactory.create(ApiService.class)
                .upload(getTokens(),params)
                .enqueue(new DefaultCallback<BaseStrEntity>() {
                    @Override
                    public void onStart(Call<BaseStrEntity> call) {
                        showLoading_base(ConversationListActivity.this);
                    }

                    @Override
                    public void onError(Call<BaseStrEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseStrEntity> call, BaseStrEntity baseEntity) {
                        if (baseEntity.getCode() == 0 ) {
                            showToast("上传成功");
                            saveChat(uid,baseEntity.getData(),1);
                        } else {
//
                        }
                    }
                });
    }


    private void showPopuSelect() {

        PopupSoftinputUtils.softinputDismiss(ConversationListActivity.this, binding.conveImg1);
        RequestPermissions.getPermissions_camera(ConversationListActivity.this,
                new RequestPermissions.SuccessInterf() {
                    @Override
                    public void onSuccess() {
                        ImageSelector.builder()
                                .useCamera(false) // 设置是否使用拍照
                                .setCrop(false)  // 设置是否使用图片剪切功能。
                                .setSingle(true)  //设置是否单选
                                .onlyImage(true)  //只要图片（不要视频）
                                .setMaxSelectCount(1)
                                .setViewImage(true) //是否点击放大图片查看,，默认为true
                                .start(ConversationListActivity.this, REQUEST_CODE); // 打开相册
                    }
                });
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        EventBus.getDefault().post(new String("home_refres"));
    }
}